<template>
  <div class="table-demo-container layout-padding">
    <div class="table-demo-padding layout-padding-view layout-padding-auto">
      <TableSearch :search="state.tableData.search" @search="onSearch" @add="onOperateHandle('add')" :isdelete="true" @delete="batchDel" />
      <Table
          ref="tableRef"
          v-bind="state.tableData"
          class="table-demo"
          @operateHandle="onOperateHandle"
          @pageChange="onTablePageChange"
          @sortHeader="onSortHeader"
          @selection-change="onSelectionChange"
      />
      <EditDialog ref="editDialogRef" @refresh="getTableData" :data="state.tableData.classify" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineAsyncComponent, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useGoodsApi } from '/@/api/shop/goods';

// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/views/shop/goods/search.vue'));
const EditDialog = defineAsyncComponent(() => import('/@/views/shop/goods/dialog.vue'));

// 定义变量内容
const tableRef = ref<RefType>();
const editDialogRef = ref();
const state = reactive({
  tableData: {
    // 列表数据（必传）
    data: [],
    // 表头内容（必传，注意格式）
    header: [
      //{ key: 'id', colWidth: '100', title: 'ID', type: 'checkbox',showType:'', isCheck: true },
      { key: 'goodsName', colWidth: '', title: '商品名称',showType:'text', isCheck: true },
      { key: 'type', colWidth: '110', title: '类型',showType:'state', isCheck: true,showColor:['info','success','info'],showTitle:['','实物商品','虚拟商品'] },
      { key: 'classifyName', colWidth: '100', title: '分类',showType:'text', isCheck: true },
      { key: 'linePrice', colWidth: '100', title: '市场价',showType:'text', isCheck: true },
      { key: 'price', colWidth: '100', title: '售价',showType:'text', isCheck: true },
      { key: 'integral', colWidth: '100', title: '积分',showType:'text', isCheck: true },
      { key: 'sku', colWidth: '100', title: '库存',showType:'text', isCheck: true },
      { key: 'total', colWidth: '100', title: '总销量',showType:'text', isCheck: true },
      { key: 'status', colWidth: '100', title: '状态',showType:'state', isCheck: true,showColor:['info','success'],showTitle:['下架','上架'] },
      { key: 'cover', colWidth: '100', title: '缩略图',showType:'image', isCheck: true },
      { key: 'sort', colWidth: '100', title: '排序',showType:'text', isCheck: true }
    ],
    // 配置项（必传）
    config: {
      total: 0, // 列表总数
      loading: false, // loading 加载
      isBorder: false, // 是否显示表格边框
      isSerialNo: false, // 是否显示表格序号
      isSelection: true, // 是否显示表格多选
      operateWidth: 110, // 操作栏宽度
      operateList: [
        {
          input: 'button',//button:按钮，popconfirm：确认按钮
          name: '编辑',//显示的文字
          title: '',//确认按钮标题
          type: 'primary',//default:黑色,info:灰色,primary:蓝色,success:绿色,warning:黄色,danger:红色
          prop: 'edit',//属性，
          disabled: 'isEdit',//部分禁用的字段名称
        },
        {
          input: 'popconfirm',//button:按钮，popconfirm：确认按钮
          name: '删除',//显示的文字
          title: '是否确认删除？',//确认按钮标题
          type: 'danger',//按钮主题类型 default:黑色,info:灰色,primary:蓝色,success:绿色,warning:黄色,danger:红色
          prop: 'del',//属性，
          disabled: 'isDel',//部分禁用的字段名称
        }
      ], // 操作栏自定义按钮
    },
    // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
    search: [],
    // 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
    param: {
      pageNum: 1,
      pageSize: 10,
    },
    // 打印标题
    printName: '表格打印',
    classify: [],
  },
  selectlist: [],
});

// 初始化表格数据
const getTableData = () => {
	state.tableData.config.loading = true;
	useGoodsApi().getAdminGoods(state.tableData.param).then(res=>{
		if(!res.code){
			state.tableData.data = res.data.data;
			state.tableData.config.total = res.data.total;
      state.tableData.search = res.data.search;
      state.tableData.classify = res.data.classify;
		}
	}).catch(err=>{
		console.log(err);
	});

	setTimeout(() => {
		state.tableData.config.loading = false;
	}, 500);
};
//搜索
const onSearch = (data: EmptyObjectType) => {
  state.tableData.param = Object.assign({}, state.tableData.param, { ...data });
  //console.log(state.tableData.param);
  tableRef.value.pageReset();
};
//操作按钮点击事件
const onOperateHandle = (type: string, row?: any) => {
  if(type === 'add' || type === 'edit'){
    editDialogRef.value.openDialog(type, row);
  }else if(type==='del'){
    rowDel(row);
  }

}
// 删除
const rowDel = (row: any) => {
    useGoodsApi().delAdminGoods({
      id:row.id,
    }).then(res=>{
      if(!res.code){
        getTableData();
        ElMessage.success(`删除${row.nickname}成功！`);
      }
    }).catch(err=>{
      console.log(err);
    });
};
//批量删除
const batchDel = () => {
	var ids = [] as any;
	state.selectlist.forEach((v) => (ids.push(v.id)));
	if(!ids.length){
		ElMessage.error('至少选择一行数据');
		return !1;
	}
	var id = ids.join();
  ElMessageBox.confirm(`确定批量删除所选记录?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
      .then(() => {
        useGoodsApi().delAdminGoods({id:id}).then(res=>{
          if(!res.code){
            ElMessage.success('批量删除成功！');
            getTableData();
            tableRef.value.clearSelection();
          }
        }).catch(err=>{
          console.log(err);
        })
      })
      .catch(() => {});
};
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
  state.tableData.param.pageNum = page.pageNum;
  state.tableData.param.pageSize = page.pageSize;
  getTableData();
};
// 表格多选改变时，用于导出
const onSelectionChange = (val: any) => {
	state.selectlist = val;
};
// 拖动显示列排序回调
const onSortHeader = (data: any) => {
  state.tableData.header = data;
};
// 页面加载时
onMounted(() => {
	getTableData();
});
</script>

<style scoped lang="scss">
.table-demo-container {
  .table-demo-padding {
    padding: 15px;
    .table-demo {
      flex: 1;
      overflow: hidden;
    }
  }
}
</style>
